<template>
  <el-dialog title="创建工具流" :visible.sync="showDetail.showProjectDialog" :before-close="cancel" align="center" width="850px">
<!--    <div style="height:450px; overflow-y: auto;padding-right: 18px">-->
    <div style="height:260px; overflow-y: auto;padding-right: 18px">
      <el-form @submit.native.prevent :model="createDetail" :rules="rules" ref="createDetail" label-width="100px">
        <el-form-item label="名称" prop="projectName" style="margin-top:30px">
          <el-input v-model="createDetail.projectName" placeholder="请定义工程名称"
                    @keyup.enter.native="submitForm('createDetail')"></el-input>
        </el-form-item>
<!--        <el-form-item label="协作团队" prop="team">-->
<!--          <el-input v-model="createDetail.team" placeholder="请输入协作团队"-->
<!--                   ></el-input>-->
<!--        </el-form-item>-->
        <!-- <el-form-item label="协作团队" class="memberChooseCss" prop="user" style="text-align: left"> -->
          <!-- <span style="position: absolute;left:-79px;color:#f56c6c;">*</span> -->
<!--          <span v-for="(item,index) in createDetail.userNameList.slice(0,8)" style="display: inline-block;">{{item +-->
<!--          ( (index + 1 ) == createDetail.userNameList.slice(0,8).length ? '' :  ' ，') +-->
<!--            ( ( index + 1 ) == createDetail.userNameList.slice(0,8).length && createDetail.userNameList.length > 8 ? ' ...' : '')}}</span>-->

                    <!-- <span v-for="(item,index) in createDetail.hasChooseMember.slice(0,8)" style="display: inline-block;">{{item.userName +
                    ( (index + 1 ) == createDetail.hasChooseMember.slice(0,8).length ? '' :  ' ，') +
                      ( ( index + 1 ) == createDetail.hasChooseMember.slice(0,8).length && createDetail.hasChooseMember.length > 8 ? ' ...' : '')}}</span>


          <el-button type="primary" size="mini" style="padding: 7px" @click="openChooseMember">选择协作团队</el-button>
        </el-form-item> -->

        <el-form-item label="密级" prop="secretLevel" style="margin-top:30px">
<!--          <el-input v-model="createDetail.secretLevel" placeholder="请输入密级"></el-input>-->

          <div class="secretBoxCss" style="text-align: left">
<!--            <span style="display: inline-block;margin-right: 28px;margin-bottom: 10px;"><span style="color: red">*</span> 请选择文档密级:</span>-->
            <el-radio-group v-model="createDetail.secretLevel">
              <el-radio :label="item.value"
                        style="margin-right: 5px;"
                        v-for="(item,index) in [{value:'1',label:'非密'},{value:'2',label:'秘密'},{value:'3',label:'机密'}]"
                        :key="index"><span :style="{fontWeight:'bolder',color:index == 0 ? 'green' : (index == 1 ? 'orange' : 'red')}">{{ item.label }}</span></el-radio>
              <!--          :disabled="item.disabled"-->
            </el-radio-group>
          </div>





        </el-form-item>
        <el-form-item label="描述" prop="describe" style="margin-top:30px">
          <el-input type="textarea" v-model="createDetail.describe" placeholder="描述" :maxlength="500"></el-input>
        </el-form-item>
<!--        <el-form-item label="工程位置" align="left">-->
<!--          <div class="tree-menu" id="createProjectTree" style="height: 135px; overflow: auto;">-->
<!--            <ul v-for="(menuItem,index) in projectList" :key="menuItem.id">-->
<!--              <SelectTree :item="menuItem"></SelectTree>-->
<!--            </ul>-->
<!--          </div>-->
<!--        </el-form-item>-->
      </el-form>

<!--      :before-close="closeChooseMemberDialog"-->
      <el-dialog
        :close-on-click-modal="false"
        :show-close="false"
        :close-on-press-escape="false"
        custom-class="chooseMemberDialogCss"
        width="820px"
        title="选择协作团队人员"
        :visible.sync="innerVisible"
        append-to-body>
        <div style="width: 780px;height: 530px">
          <p class="memberTitleBox"><span>选择部门：</span><span>选择协作团队人员：</span><span>已选协作团队人员：</span></p>
          <div class="deptBox">
            <p class="everyDeptCss" v-for="(item,index) in deptList"
               :style="{backgroundColor:item.id.toString() === nowChooseDept.id.toString() ? 'rgba(0,0,0,0.06)' : ''}"
               @click="chooseDeptFunc(item)">{{item.deptName}}</p>
            <p class="everyDeptCss" v-if="deptList.length < 1" style="text-align: center;color:rgba(0,0,0,0.4)">无数据</p>
          </div>
          <div class="memberBox">
            <p class="everyMemberCss" v-for="(item,index) in userData">
              <span class="everyMemberCss-name">{{item.userName}}</span>
              <span class="everyMemberCss-icon el-icon-plus" @click="addSingleMember(item)"></span>
            </p>
            <p class="everyMemberCss" v-if="userData.length < 1" style="text-align: center;color:rgba(0,0,0,0.4)">无数据</p>
          </div>
          <div class="memberBox-hasChoose">
            <p class="everyMemberCss" v-for="(item,index) in createDetail.hasChooseMember">
              <span class="everyMemberCss-name">{{item.userName}}</span>
              <span class="everyMemberCss-icon el-icon-close" style="color: red;font-weight: bolder" @click="deleteSingleMember(item,index)"></span>
            </p>
            <p class="everyMemberCss" v-if="createDetail.hasChooseMember.length < 1" style="text-align: center;color:rgba(0,0,0,0.4)">无数据</p>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
<!--          <el-button @click="closeChooseMemberDialog" size="small">取 消</el-button>-->
          <el-button type="primary" @click="confirmChooseMember" size="small">确定</el-button>
        </div>
      </el-dialog>

    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="resetForm">重置</el-button>
      <el-button :disabled="disabled" type="primary" @click="submitForm('createDetail')">确定</el-button>
    </div>
  </el-dialog>
</template>
<style scoped>
.el-form-item {
  margin-bottom: 20px;
}
.memberChooseCss {
  position: relative;
}
.deptBox {
  width: 218px;
  margin-right: 10px;
  height: 500px;
  /*background-color: forestgreen;*/
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  padding: 10px;
  float: left;
  overflow-y: auto;
}
.memberBox {
  width: 218px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  margin-right: 10px;
  padding: 10px;
  height: 500px;
  /*background-color: gold;*/
  float: left;
  overflow-y: auto;
}
.memberBox-hasChoose {
  width: 258px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  padding: 10px;
  height: 500px;
  /*background-color: brown;*/
  float: left;
  overflow-y: auto;
}

.memberTitleBox {
  width: 100%;
  height: 30px;
  line-height: 30px;
}
.memberTitleBox span {
  display: inline-block;
  padding-left: 10px;
}
.memberTitleBox span:first-child {
  width: 240px;
  /*background-color: blue;*/
}
.memberTitleBox span:nth-child(2) {
  width: 240px;
  /*background-color: violet;*/
}
.memberTitleBox span:nth-child(3) {
  width: 270px;
  /*background-color: hotpink;*/
}

.everyDeptCss {
  width: calc(100% - 10px);
  padding-left: 10px;
  height: 26px;
  line-height: 26px;
  cursor: pointer;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin-bottom: 8px;
}
.everyDeptCss:hover {
  background-color: rgba(0, 0, 0, 0.06);
}

.everyMemberCss {
  width: calc(100% - 10px);
  /*background-color: forestgreen;*/
  padding-left: 10px;
  height: 26px;
  line-height: 26px;
  /*cursor: pointer;*/
  margin-bottom: 8px;
}
.everyMemberCss-name {
  display: inline-block;
  width: calc(100% - 30px);
  height: 26px;
  line-height: 26px;
  /*background-color: violet;*/
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  float: left;
}
.everyMemberCss-icon {
  display: inline-block;
  /*background-color: firebrick;*/
  width: 30px;
  height: 26px;
  line-height: 26px;
  float: left;
  text-align: center;
  cursor: pointer;
}
.everyMemberCss:hover {
  background-color: rgba(0, 0, 0, 0.06);
}
</style>
<script>
import SelectTree from "./create_project_dialog/SelectTree.vue";
import {
  getAllDeptList,
  queryUserFromDeptId
} from "../../../../api/sourceDetail";

export default {
  name: "CreateProjectDialog",
  data() {
    var projectNameValidator = (rule, value, callback) => {
      var reg = /^(?! +$).+/;
      if (!reg.test(value) || value == null) {
        callback(new Error("不能为空或空字符串"));
      } else if (value.trim().length > 100) {
        callback(new Error("长度在 1 到 100 个字符"));
      }
      callback();
    };
    return {
      rules: {
        //校验规则
        projectName: [
          { required: true, validator: projectNameValidator, trigger: "blur" }
        ],
        describe: [
          { required: false, message: "请填写描述信息", trigger: "blur" }
        ],
        secretLevel: [
          { required: false, message: "请填写协作团队", trigger: "blur" }
        ],
        team: [{ required: false, message: "请填写密级", trigger: "blur" }],
        user: [
          { required: false, message: "请选择协作团队人员", trigger: "blur" }
        ]
      },
      disabled: false, //确认按钮点击后并不能重复点击
      createDetail: {
        //创建工程的信息
        projectName: "", //工程名
        describe: "", //描述
        paralleled: false, //模式，是否支持分布式
        parentId: "", //父类id
        team: "", //协作团队   // 2023-01-12 被 hasChooseMember 替代
        secretLevel: "", //密级

        // chooseDeptIdList:[],//已经选的人员的部门的id
        // userIdList:[],//人员id列表
        // userNameList:['张三','李四','王五','张三','李四','王五','张三','李四','王五','张三','李四','王五'],//人员列表

        hasChooseMember: []
      },
      nowChooseDept: {
        //当前选择的部门
        id: "",
        name: ""
      },

      deptList: [], //部门列表
      userData: [], //当前部门下所有人员列表
      innerVisible: false
    };
  },
  computed: {
    flowData: function() {
      return this.$store.state.project.flowData;
    },
    showDetail: function() {
      //弹出框是否显示
      return this.$store.state.project.projectMenuModel.showDetail;
    },
    rightContentTargetItem: function() {
      return this.flowData.rightContentTargetItem;
    },
    projectList: function() {
      //工程列表数据
      return this.$store.state.project.projectMenu;
    }
  },
  components: {
    SelectTree
  },
  methods: {
    //打开选择人员弹框
    openChooseMember() {
      getAllDeptList().then(res => {
        // console.log(res);
        if (res.status === "SUCCESS") {
          this.deptList = res.data;
        }
      });
      this.innerVisible = true;
    },

    //选择部门
    chooseDeptFunc(item) {
      this.nowChooseDept = {
        id: item.id,
        name: item.deptName
      };
      queryUserFromDeptId(item.id).then(res => {
        // console.log(res);
        if (res.status === "SUCCESS") {
          this.userData = res.data;
        }
      });
    },

    //添加一个人员
    addSingleMember(item) {
      // console.log(item,this.createDetail.hasChooseMember);
      let allChooseUserIdList = [];
      this.createDetail.hasChooseMember.length &&
        this.createDetail.hasChooseMember.forEach(val => {
          allChooseUserIdList.push(val.id);
        });
      if (allChooseUserIdList.length < 1) {
        this.createDetail.hasChooseMember = this.createDetail.hasChooseMember.concat(
          item
        );
      } else {
        if (allChooseUserIdList.indexOf(item.id) >= 0) {
          this.$message.info("已选该人员！");
          return;
        } else {
          this.createDetail.hasChooseMember = this.createDetail.hasChooseMember.concat(
            item
          );
        }
      }
    },

    //删除一个人员
    deleteSingleMember(item, index) {
      this.createDetail.hasChooseMember.splice(index, 1);
    },

    // //取消关闭、选择人员
    // closeChooseMemberDialog(){
    //   this.innerVisible = true
    // },

    //确认人选择人员
    confirmChooseMember() {
      this.innerVisible = false;
      this.nowChooseDept = {
        //当前选择的部门
        id: "",
        name: ""
      };
      this.userData = []; //当前部门下所有人员列表
    },

    resetForm() {
      //重置
      // this.$refs.createDetail.resetFields();
      this.createDetail.projectName = "";
      this.createDetail.describe = "";
      this.createDetail.paralleled = false;
      this.createDetail.secretLevel = "";
      this.createDetail.team = "";
      this.createDetail.hasChooseMember = [];
    },
    cancel() {
      this.showDetail.showFastCreateProjectDialog = false;
      this.showDetail.showProjectDialog = false;
      this.$refs.createDetail.clearValidate();

      //重置
      // this.$refs.createDetail.resetFields();
      this.createDetail.projectName = "";
      this.createDetail.describe = "";
      this.createDetail.paralleled = false;
      this.createDetail.secretLevel = "";
      this.createDetail.team = "";
      this.createDetail.hasChooseMember = [];
    },
    submitForm(formName) {
      //确认
      // this.disabled = true;
      this.$refs[formName].validate(valid => {
        if (valid) {
          // console.log(this.createDetail.hasChooseMember);
          // if (this.createDetail.hasChooseMember.length < 1) {
          //   this.$message.info("请选择协作团队人员！");
          //   this.disabled = false;
          //   return;
          // }
          if (!this.createDetail.secretLevel) {
            this.$message.info("请选择密级！");
            this.disabled = false;
            return;
          }

          this.createProject();
        } else {
          console.log("error submit!!");
          this.disabled = false;
          return false;
        }
      });
    },
    createProject: function() {
      // console.log(JSON.parse(JSON.stringify(this.createDetail.hasChooseMember)));
      let params_deptIdList = [];
      let params_userNameList = [];
      this.createDetail.hasChooseMember.forEach(val => {
        params_deptIdList.push(val.deptId);
        params_userNameList.push(val.userName);
      });
      params_deptIdList = [...new Set(params_deptIdList)].toString();
      params_userNameList = [...new Set(params_userNameList)].toString();
      // console.log(params_deptIdList,params_userNameList);
      // return

      //如果当前项为文件夹时，设置当前项为父类项
      this.flowData.currentParentItem = this.flowData.rightContentTargetItem;
      var that = this;
      var data = {};
      data["paralleled"] = this.createDetail.paralleled;
      data["name"] = this.createDetail.projectName;
      data["parentId"] = this.rightContentTargetItem.id;
      data["description"] = this.createDetail.describe;
      data["team"] = this.createDetail.team;
      data["secretLevel"] = this.createDetail.secretLevel;
      data["deptId"] = params_deptIdList;
      data["userName"] = params_userNameList;

      // console.log(data);
      // return
      this.$.ajax({
        url: that.$store.state.global.httpServer + "/api/project/",
        method: "post",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(data),
        beforeSend: function(xhr) {
          xhr.setRequestHeader("accessToken", localStorage.accessToken);
        },
        success: function(data) {
          switch (data.status) {
            case "SUCCESS":
              that.$notify({
                title: "成功",
                message: data.message,
                type: "success"
              });
              //设置状态为正在切换
              that.flowData.projectChange = true;
              //隐藏对话框
              that.showDetail.showProjectDialog = false;
              //获取添加子目录
              that.$store.dispatch("getMenuProjectList", 3);
              //设置当前添加项为当前选中项
              that.setCurrentSelectItem(data.data);
              that.flowData.currentProjectDetail.id = data.data;
              //获取添加的工程及工程数据
              that.$store.dispatch("getCurrentFlowJson", data.data);
              that.resetForm(); //添加完成后重置表单
              break;
            case "FAIL":
              that.$notify.error({
                title: "错误",
                message: data.message
              });
              break;
          }
          //修改按钮的可被点击状态
          that.disabled = false;
          that.$emit("doingGetNewData");
        },
        error: function(data) {
          var msg = JSON.parse(data.responseText);
          that.$notify.error({
            title: "错误",
            message: msg.message
          });
          //修改按钮的可被点击状态
          that.disabled = false;
        }
      });
    },
    setCurrentSelectItem: function(docId) {
      var that = this;
      try {
        setTimeout(function() {
          var currentItem =
            (that.flowData.currentParentItem.children &&
              that.flowData.currentParentItem.children.filter(
                node => (node.project ? node.project.id == docId : false)
              )) ||
            [];
          if (currentItem.length == 0) {
            that.setCurrentSelectItem(docId);
          } else {
            that.flowData.currentProjectItem = currentItem[0];
            //                            //设置当前操作工程信息
            that.flowData.currentProjectDetail = currentItem[0].project;
            //                            that.$store.state.menuProject.workFlowSocket = null;
            that.$store.commit(
              "updateMenuProjectSelectComponent",
              "ProjectContentMsg"
            );
          }
        }, 200);
      } catch (e) {
        console.error(e.message);
      }
    }
  }
};
</script>
